package user_sql

import (
	"errors"
	"gorm.io/gorm"
	"my-systems/pet-system/internal/db"
	"my-systems/pet-system/internal/models"
)

var DB *gorm.DB

// InitDB 初始化 DB 变量的函数
func InitDB(db *gorm.DB) {
	DB = db
}

func RegisterUserMethod(us *models.User) error {
	return db.DB.Create(us).Error
}

func ExistOrNotByUsername(username string) (user *models.User, exist bool, err error) {
	user = &models.User{}
	err = db.DB.Where("username = ?", username).First(user).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, false, nil
		}
		return nil, false, err
	}
	return user, true, nil
}

func UpdateUserInfo(tx *gorm.DB, uid int, user *models.User) error {
	if tx == nil {
		tx = db.DB
	}
	// 只更新有变化的值
	err := tx.Model(&models.User{}).Where("id = ?", uid).Updates(&user).Error
	return err
}

func GetUserByID(uid int) (user *models.User, err error) {
	err = db.DB.Model(&models.User{}).Where("id = ?", uid).First(&user).Error
	return user, err
}

func UpAvatar(uid int, user *models.User) error {
	return db.DB.Model(&models.User{}).Where("id=?", uid).Updates(&user).Error
}
